package main

import (
	"context"
	"encoding/json"
	httptransport "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"github.com/joho/godotenv"
	"gysa-share01/common"
	"gysa-share01/exception"
	user_service "gysa-share01/user-service"
	"gysa-share01/user-service/auth"
	"log"
	"net/http"
)

func main() {
	logger := common.Logger
	//加载.env
	err := godotenv.Load()
	if err != nil {
		logger.Println("Error loading .env file")
	}

	service := auth.AuthService{}
	//添加日志中间件
	registerLogic := auth.MakeRegisterByPwdEndpoint(service)
	registerLogic = auth.LogMiddleware(logger)(registerLogic)

	registerHandle := httptransport.NewServer(
		registerLogic,
		auth.DecodeRegisterByPwdRequest,
		auth.EncodeResponse,
		httptransport.ServerErrorEncoder(errHandler),
	)
	//登陆
	loginLogic := auth.MakeLoginEndpoint(service)
	loginLogic = auth.LogMiddleware(logger)(loginLogic)

	loginHandle := httptransport.NewServer(
		loginLogic,
		auth.DecodeLoginRequest,
		auth.EncodeResponse,
		httptransport.ServerErrorEncoder(errHandler),
	)
	r := mux.NewRouter()
	r.Handle("/auth/register", registerHandle).Methods("POST")
	r.Handle("/auth/login", loginHandle).Methods("POST")

	//mymux := http.NewServeMux()
	http.Handle("/", r)

	logger.Fatal(http.ListenAndServe(user_service.HttpHost+":"+user_service.HttpPort, nil))

}

func errHandler(ctx context.Context, err error, w http.ResponseWriter) {
	w.Header().Set("Content-Type", "application/json;charset=utf-8")
	exceptions, ok := err.(exception.ExceptionInterface)
	resp := common.Response{
		ErrorCode: exception.SYSTEM_ERROR,
		ErrorMsg:  "服务器繁忙",
	}
	if ok && exceptions.ECode() > 0 {
		w.WriteHeader(400)
		resp.ErrorCode = exceptions.ECode()
		resp.ErrorMsg = exceptions.Error()
	} else {
		w.WriteHeader(500)
		log.Println(err)
	}
	json.NewEncoder(w).Encode(resp)
}
